package gatewaylogic

import (
	"context"

	"go-zero-admin/apps/modules/iot/cmd/link/gateway/constant"
	"go-zero-admin/apps/modules/iot/cmd/rpc/internal/svc"
	"go-zero-admin/apps/modules/iot/cmd/rpc/iotpb"
	"go-zero-admin/apps/modules/iot/model"
	"go-zero-admin/pkg/tool"
	"go-zero-admin/pkg/xerr"

	"github.com/duke-git/lancet/v2/convertor"
	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
)

type UpGatewayLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpGatewayLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpGatewayLogic {
	return &UpGatewayLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UpGatewayLogic) UpGateway(in *iotpb.UpGatewayReq) (*iotpb.UpGatewayResp, error) {
	gateway := in.GetParams()
	if gateway == nil || gateway.GetId() == 0 || gateway.GetDeptId() == 0 ||
		gateway.GetName() == "" || gateway.GetConfiguration() == "" || gateway.GetProvider() == "" ||
		gateway.GetUpdateUser() == "" {
		return nil, errors.Wrapf(xerr.NewErrMsg("更新设备网关失败：参数缺失"),
			tool.GetErrMsgFormat("update gateway"), "params is not existed", in)
	}

	// 获取数据
	one, err := l.svcCtx.IotGatewayModel.FindOne(l.ctx, gateway.GetId())
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrFindOneCode(err, model.ErrNotFound),
			tool.GetErrMsgFormat("update gateway"), err, in)
	}

	// 判断是否已经开启 开启的不让更新
	if one.State == constant.GatewayStateOpen {
		return nil, errors.Wrapf(xerr.NewErrMsg("更新设备网关失败：ID："+
			convertor.ToString(one.Id)+"，名称："+one.Name+"，已启动，请关闭后再更新"),
			tool.GetErrMsgFormat("update gateway"),
			"gateway id: "+convertor.ToString(one.Id)+", name: "+one.Name+", is opened", one)
	}
	one.DeptId = gateway.GetDeptId()
	one.Name = gateway.GetName()
	one.Configuration = gateway.GetConfiguration()
	one.State = gateway.GetState()
	one.Provider = gateway.GetProvider()
	one.Description = gateway.GetDescription()
	one.UpdateUser = gateway.GetUpdateUser()

	// 更新
	err = l.svcCtx.IotGatewayModel.UpdateEx(l.ctx, nil, one)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrFindOneCode(err, model.ErrNotFound),
			tool.GetErrMsgFormat("update gateway"), err, in)
	}

	return &iotpb.UpGatewayResp{}, nil
}
